<template>
  <view class="container">
    <!-- 顶部服务信息 -->
    <view class="header-card">
      <view class="store-service-info">
        <text class="store-name">{{ store.name }}</text>
        <text class="service-name">{{ service.name }}</text>
      </view>
      <view class="service-price">￥{{ finalPrice }}</view>
    </view>

    <!-- 宠物选择 -->
    <view class="section">
      <text class="section-title">选择宠物</text>
      <scroll-view scroll-x class="pet-scroll">
        <view
          v-for="pet in pets"
          :key="pet.id"
          class="pet-card"
          :class="{ selected: selectedPet && selectedPet.id === pet.id }"
          @click="viewPetDetail(pet)"
        >
          <image class="pet-avatar" src="/static/icons/dog.png"></image>
          <view class="pet-info-box">
            <text class="pet-name">{{ pet.name }}</text>
            <view
              v-if="selectedPet && selectedPet.id === pet.id && petDetail.id === pet.id"
              class="pet-detail-inline"
            >
              <text class="pet-meta">类型：{{ petDetail.type || '-' }}</text>
              <text class="pet-meta">品种：{{ petDetail.breed || '-' }}</text>
              <text class="pet-meta">性别：{{ genders[petDetail.gender] }}</text>
              <text class="pet-meta">年龄：{{ petDetail.age || '-' }} 岁</text>
              <text class="pet-meta">体重：{{ petDetail.weight || '-' }} kg</text>
              <view class="btn-row">
                <button size="mini" @click.stop="openPetForm('edit', petDetail)">编辑</button>
                <button size="mini" type="warn" @click.stop="deletePet(petDetail.id)">删除</button>
              </view>
            </view>
          </view>
        </view>
        <view class="pet-card add" @click="openPetForm('add')">
          <text class="add-icon">+</text>
          <text class="pet-name">添加</text>
        </view>
      </scroll-view>
    </view>

    <!-- 地址 (仅上门服务) -->
    <view v-if="service.type && service.type.includes('上门')" class="section">
      <text class="section-title">服务地址</text>
      <view v-if="!selectedAddress" class="no-address">
        <text>暂无地址，请添加</text>
        <button size="mini" @click="goAddressPage">添加地址</button>
      </view>
      <view v-else class="address-card selected">
        <view class="addr-info">
          <text class="contact">{{ selectedAddress.contactName }} {{ selectedAddress.contactPhone }}</text>
          <text class="detail">
            {{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }} {{ selectedAddress.address }}
          </text>
        </view>
        <view class="address-actions">
          <button size="mini" @click="goAddressPage">修改</button>
        </view>
      </view>
    </view>

    <!-- 日期 + 时间段 -->
    <view class="section datetime-section">
      <text class="section-title">选择日期与时间</text>
      <view class="datetime-container">
        <scroll-view scroll-y class="date-list">
          <view
            v-for="(day, idx) in dates"
            :key="idx"
            class="date-item"
            :class="{ selected: selectedDate === day.date }"
            @click="selectDate(day.date)"
          >
            <text class="day">{{ day.label }}</text>
            <text class="date">{{ day.date }}</text>
          </view>
        </scroll-view>

        <scroll-view scroll-y class="time-list">
          <view class="time-grid">
            <view
              v-for="slot in timeSlots"
              :key="slot.id"
              class="time-btn"
              :class="{ 
                disabled: slot.bookedCount >= slot.maxCapacity, 
                selected: selectedSlot && selectedSlot.id === slot.id 
              }"
              @click="slot.bookedCount < slot.maxCapacity && selectSlot(slot)"
            >
              <text class="time-text">{{ slot.timeSlot }}</text>
              <text class="capacity">
                {{ slot.maxCapacity - slot.bookedCount > 0 ? '余' + (slot.maxCapacity - slot.bookedCount) : '已满' }}
              </text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 优惠券 -->
    <!-- <view class="section">
      <text class="section-title">优惠券</text>
      <view class="coupon-box" @click="goSelectCoupon">
        <text>{{ selectedCoupon ? selectedCoupon.name : '未选择' }}</text>
        <text class="arrow">›</text>
      </view>
    </view> -->

    <!-- 底部栏 -->
    <view class="bottom-bar">
      <!-- <view class="price-box">
        <text class="label">应付</text>
        <text class="amount">￥{{ finalPrice }}</text>
      </view> -->
      <button class="btn-confirm" @click="submitReservation">立即预约</button>
    </view>

    <!-- 宠物表单 -->
    <view v-if="showPetForm" class="popup-mask" @click="closePetForm">
      <view class="popup" @click.stop>
        <text class="popup-title">{{ formMode === 'add' ? '添加宠物' : '编辑宠物' }}</text>
        <view class="form">
          <input v-model="petForm.name" placeholder="宠物名称" class="form-input" />
          <input v-model="petForm.type" placeholder="类型（如狗/猫）" class="form-input" />
          <input v-model="petForm.breed" placeholder="品种" class="form-input" />
          <picker mode="selector" :range="genders" @change="e => petForm.gender = parseInt(e.detail.value)">
            <view class="picker">性别：{{ genders[petForm.gender] }}</view>
          </picker>
          <input v-model="petForm.age" type="number" placeholder="年龄(岁)" class="form-input" />
          <input v-model="petForm.weight" type="digit" placeholder="体重(kg)" class="form-input" />
          <picker mode="selector" :range="yesNo" @change="e => petForm.neutered = parseInt(e.detail.value)">
            <view class="picker">是否绝育：{{ yesNo[petForm.neutered] }}</view>
          </picker>
          <picker mode="selector" :range="yesNo" @change="e => petForm.vaccinated = parseInt(e.detail.value)">
            <view class="picker">是否接种疫苗：{{ yesNo[petForm.vaccinated] }}</view>
          </picker>
          <textarea v-model="petForm.remark" placeholder="备注" class="form-textarea"></textarea>
        </view>
        <button class="submit-btn" @click="submitPetForm">保存</button>
      </view>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request.js'

export default {
  data() {
    return {
      store: {},
      service: {},
      pets: [],
      selectedPet: null,
      petDetail: {},
      addresses: [],
      selectedAddress: null,
      dates: [],
      selectedDate: null,
      timeSlots: [],
      selectedSlot: null,
      selectedCoupon: null,
      finalPrice: 0,
      storeId: null,
      serviceId: null,
      showPetForm: false,
      formMode: 'add',
      petForm: {},
      genders: ['未知', '弟弟', '妹妹'],
      yesNo: ['否', '是']
    }
  },
  async onLoad(options) {
    this.storeId = options.storeId || (uni.getStorageSync('reservationParams')?.storeId)
    this.serviceId = options.serviceId || (uni.getStorageSync('reservationParams')?.serviceId)
    await this.loadInitData()

    if (this.pets.length > 0) {
      this.selectedPet = this.pets[0]
      await this.viewPetDetail(this.selectedPet)
    }
    if (this.dates.length > 1) {
      this.selectedDate = this.dates[1].date
      await this.selectDate(this.selectedDate)
    }
  },
  onShow() {
    const user = uni.getStorageSync('user')
    if (user && user.userId && this.service.type && this.service.type.includes('上门')) {
      this.loadAddress(user.userId)
    }
  },
  methods: {
    async loadInitData() {
      const storeRes = await request({ url: `/store/${this.storeId}`, method: 'GET' })
      if (storeRes.code === 200) this.store = storeRes.data

      const serviceRes = await request({ url: `/service/${this.serviceId}`, method: 'GET' })
      if (serviceRes.code === 200) {
        this.service = serviceRes.data
        this.finalPrice = serviceRes.data.price
      }

      const user = uni.getStorageSync('user')
      if (user && user.userId) {
        const petRes = await request({ url: `/pet/list/${user.userId}`, method: 'GET' })
        if (petRes.code === 200) this.pets = petRes.data
        await this.loadAddress(user.userId)
      }

      this.dates = this.getNext7Days()
    },
    async loadAddress(userId) {
      const addrRes = await request({ url: `/user-address/${userId}`, method: 'GET' })
      if (addrRes.code === 200) {
        this.addresses = addrRes.data || []
        this.selectedAddress = this.addresses.find(a => a.isDefault === 1) || this.addresses[0] || null
      }
    },
    getNext7Days() {
      const days = []
      const now = new Date()
      const weekDays = ['日','一','二','三','四','五','六']
      for (let i = 0; i < 7; i++) {
        const d = new Date()
        d.setDate(now.getDate() + i)
        days.push({
          date: d.toISOString().split('T')[0],
          label: ['今天', '明天', '后天'][i] || `周${weekDays[d.getDay()]}`
        })
      }
      return days
    },
    async selectDate(date) {
      this.selectedDate = date
      const res = await request({
        url: `/service-schedule/list`,
        method: 'GET',
        data: { storeId: this.storeId, serviceId: this.serviceId, date }
      })
      if (res.code === 200) this.timeSlots = res.data
    },
    selectSlot(slot) { this.selectedSlot = slot },
    goSelectCoupon() { uni.navigateTo({ url: '/pages/coupon/select' }) },
    goAddressPage() { uni.navigateTo({ url: '/pages/address/address' }) },

    async viewPetDetail(pet) {
      const user = uni.getStorageSync('user')
      const res = await request({ url: `/pet/${pet.id}`, method: 'GET', data: { userId: user.userId } })
      if (res.code === 200) {
        this.petDetail = res.data
        this.selectedPet = pet
      }
    },
    openPetForm(mode, pet = {}) {
      this.formMode = mode
      this.petForm = mode === 'edit' ? { ...pet } : { gender: 0, neutered: 0, vaccinated: 0 }
      this.showPetForm = true
    },
    closePetForm() { this.showPetForm = false },
    async submitPetForm() {
      const user = uni.getStorageSync('user')
      this.petForm.userId = user.userId
      const url = this.formMode === 'add' ? '/pet/add' : '/pet/update'
      const method = this.formMode === 'add' ? 'POST' : 'PUT'
      const res = await request({ url, method, data: this.petForm })
      if (res.code === 200) {
        uni.showToast({ title: '保存成功', icon: 'success' })
        this.showPetForm = false
        this.loadInitData()
      }
    },
    async deletePet(id) {
      const user = uni.getStorageSync('user')
      const res = await request({ url: `/pet/delete/${user.userId}/${id}`, method: 'DELETE' })
      if (res.code === 200) {
        uni.showToast({ title: '删除成功', icon: 'success' })
        this.loadInitData()
      }
    },
    async submitReservation() {
  if (!this.selectedPet) return uni.showToast({ title: '请选择宠物', icon: 'none' })
  if (this.service.type.includes('上门') && !this.selectedAddress) return uni.showToast({ title: '请选择服务地址', icon: 'none' })
  if (!this.selectedDate || !this.selectedSlot) return uni.showToast({ title: '请选择时间', icon: 'none' })

  const user = uni.getStorageSync('user')
  const res = await request({
    url: '/reservation/create',
    method: 'POST',
    data: {
      userId: user.userId,
      storeId: this.storeId,
      petId: this.selectedPet.id,
      serviceId: this.serviceId,
      scheduleId: this.selectedSlot.id,
      addressId: this.service.type.includes('上门') ? this.selectedAddress.id : null,
      couponId: this.selectedCoupon ? this.selectedCoupon.id : null,
      price: this.finalPrice
    }
  })
  if (res.code === 200) {
    uni.showToast({ title: '预约成功', icon: 'success' })
    // 改为跳转到预约列表
    uni.switchTab({ url: '/pages/reservation/list' })
  }
}

  }
}
</script>


<style scoped>
.container { background: #f8f8f8; min-height: 100vh; padding-bottom: 120rpx; }

/* 卡片 */
.header-card { display: flex; justify-content: space-between; align-items: center; background: #fff; padding: 24rpx; border-radius: 16rpx; margin: 20rpx; box-shadow: 0 4rpx 10rpx rgba(0,0,0,0.05); }
.store-name { font-size: 32rpx; font-weight: 600; }
.service-name { font-size: 26rpx; color: #888; margin-top: 6rpx; }
.service-price { font-size: 36rpx; font-weight: 600; color: #ff6a00; }

.section { margin: 20rpx; }
.section-title { font-size: 28rpx; font-weight: 600; margin-bottom: 16rpx; display: block; }

/* 宠物 */
.pet-scroll { display: flex; flex-direction: row; }
.pet-card { min-width: 300rpx; background: #fff; border-radius: 12rpx; margin-right: 20rpx; padding: 20rpx; display: flex; flex-direction: row; align-items: flex-start; box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05); }
.pet-card.selected { border: 2rpx solid #007aff; }
.pet-card.add { justify-content: center; align-items: center; flex-direction: column; }
.pet-avatar { width: 80rpx; height: 80rpx; border-radius: 50%; margin-right: 20rpx; }
.pet-info-box { display: flex; flex-direction: column; gap: 6rpx; }
.pet-name { font-size: 28rpx; font-weight: 600; }
.pet-meta { font-size: 24rpx; color: #666; }
.btn-row { display: flex; gap: 20rpx; margin-top: 10rpx; }

/* 地址 */
.no-address { background: #fff; border-radius: 12rpx; padding: 30rpx; text-align: center; font-size: 28rpx; color: #999; }
.address-card { background: #fff; border-radius: 12rpx; padding: 20rpx; box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05); }
.address-card.selected { border: 2rpx solid #007aff; }
.addr-info { font-size: 26rpx; color: #333; margin-bottom: 10rpx; }
.contact { font-weight: 600; }
.detail { font-size: 24rpx; color: #666; }
.address-actions { text-align: right; }

/* 日期 + 时间 */
.datetime-container { display: flex; height: 400rpx; background: #fff; border-radius: 12rpx; overflow: hidden; }
.date-list { width: 200rpx; background: #f7f7f7; }
.date-item { padding: 20rpx; border-bottom: 1rpx solid #eee; text-align: center; font-size: 26rpx; color: #333; }
.date-item.selected { background: #007aff; color: #fff; }
.time-list { flex: 1; padding: 20rpx; }
.time-grid { display: flex; flex-direction: column; gap: 20rpx; }
.time-btn { padding: 20rpx; border-radius: 8rpx; background: #f1f1f1; display: flex; justify-content: space-between; }
.time-btn.selected { border: 2rpx solid #007aff; background: #e6f0ff; }
.time-btn.disabled { background: #eee; color: #aaa; }

/* 优惠券 */
/* .coupon-box { background: #fff; border-radius: 12rpx; padding: 20rpx; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05); }
.arrow { font-size: 28rpx; color: #999; } */

/* 底部栏 */
.bottom-bar { position: fixed; bottom: 0; left: 0; right: 0; background: #fff; padding: 20rpx; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 -2rpx 6rpx rgba(0,0,0,0.05); }
.price-box { font-size: 28rpx; }
.amount { font-size: 36rpx; font-weight: 600; color: #ff6a00; margin-left: 10rpx; }
.btn-confirm { background: #007aff; color: #fff; border-radius: 50rpx; padding: 16rpx 50rpx; font-size: 30rpx; font-weight: 600; }

/* 弹窗 */
.popup-mask { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center; }
.popup { background: #fff; padding: 30rpx; border-radius: 16rpx; width: 80%; }
.popup-title { font-size: 32rpx; font-weight: 600; margin-bottom: 20rpx; display: block; }
.form { display: flex; flex-direction: column; gap: 20rpx; }
.form-input, .form-textarea { border: 1rpx solid #ddd; border-radius: 8rpx; padding: 16rpx; font-size: 28rpx; }
.picker { padding: 20rpx; border: 1rpx solid #ddd; border-radius: 8rpx; font-size: 28rpx; color: #333; }
.submit-btn { background: #007aff; color: #fff; margin-top: 20rpx; border-radius: 50rpx; }
</style>
